﻿/// <copyright file="PacketStack.cs" company="not for commercial use">
/// Copyright (c) 7/4/2012 All Right Reserved
/// </copyright>
/// <author>Dimitry Kaplin</author>
/// <date>7/4/2012 16:22 </date>
/// <summary>Packet stack - not really stack - queue ;-)</summary>
using System;
using System.Collections.Generic;
using System.Text;
using EthernetTools.Utils;

namespace EthernetTools.Packets
{
    public class PacketQueue
    {
        public delegate void PacketEnqueuedDelegate();

        public static event PacketEnqueuedDelegate PacketEnqueued;

        public static object atomicInContext = new Object();

        private static List<byte[]> PacketWaitingForProcessList = new List<byte[]>(1024);

        public static int PacketCount
        {
            get { return PacketWaitingForProcessList.Count; }
        }

        public static bool IsEmpty
        {
            get
            {
                return PacketWaitingForProcessList.Count == 0;
            }
        }

        /// <summary>
        /// Adds packet to queue
        /// </summary>
        /// <param name="element"></param>
        public static void Enqueue(byte[] element, ulong elementSize = 0)
        {
            try
            {
                if (elementSize > 0)
                {
                    PacketWaitingForProcessList.Add(ByteUtils.RemoveBytes(elementSize, ref element));
                }
                else
                {
                    PacketWaitingForProcessList.Add(element);
                }

                if (PacketEnqueued != null)
                {
                    PacketEnqueued();
                }
            }
            catch (System.Exception ex)
            {
                EthernetTools.MainWindow.LogWriteLine("Exception occured in PacketStack.Enqueue(): " + Environment.NewLine
                    + ex.Message, Options.Global.LogLevel.Assert);
            }
        }

        /// <summary>
        /// Return first element in queue, null if queue empty
        /// </summary>
        /// <returns></returns>
        public static byte[] Dequeue()
        {
            if (PacketWaitingForProcessList.Count == 0)
                return null;

            byte[] ret = PacketWaitingForProcessList[0];
            PacketWaitingForProcessList.RemoveAt(0);

            return ret;
        }

        public static void Clear()
        {
            PacketWaitingForProcessList.Clear();
        }
    }
}
